<?php
require_once 'common.php';
$params = require_once 'params.php';

if (isset($_REQUEST['demo'])) {
    $route = $_REQUEST['demo'];
    switch ($route) {
        case 'agentpay';
            $info = $params['agentpay'];
            break;
        case 'collection';
            $info = $params['collection'];
            break;
        case 'idCardVerify';
            $info = $params['idCardVerify'];
            break;
        case 'queryBalance';
            $info = $params['queryBalance'];
            break;
        case 'queryAgentpayFee';
            $info = $params['queryAgentpayFee'];
            break;
        case 'queryOrder';
            $info = $params['queryOrder'];
            break;
        case 'realNameVerify';
            $info = $params['realNameVerify'];
            break;
        case 'getClearFileContent';
            $info = $params['getClearFileContent'];
            break;
        default;
            echo '没有demo:' . $route;
            exit;
    }
} else {
    echo '缺少参数demo';
    exit;
}

// step1: 拼接报文及配置
$transCode = $info['transCode']; // 交易码
$accessType = '0'; // 接入类型 0-商户接入，默认；1-平台接入
$merId = $info['merId']; // 此处更换商户号
$path = $info['url']; // 服务地址
$pt = $info['pt']; // 报文

// step2: 生成AESKey并使用公钥加密
$AESKey = aes_generate(16);
$encryptKey = RSAEncryptByPub($AESKey, $pubKey);

// step3: 使用AESKey加密报文
$encryptData = AESEncrypt($pt, $AESKey);

// step4: 使用私钥签名报文
$sign = sign($pt, $priKey);

// step5: 拼接post数据
$post = array(
    'transCode' => $transCode,
    'accessType' => $accessType,
    'merId' => $merId,
    'encryptKey' => $encryptKey,
    'encryptData' => $encryptData,
    'sign' => $sign
);

// step6: post请求
$result = http_post_json(API_HOST . $path, $post);
parse_str($result, $arr);

try {
    // step7: 使用私钥解密AESKey
    $decryptAESKey = RSADecryptByPri($arr['encryptKey'], $priKey);

    // step8: 使用解密后的AESKey解密报文
    $decryptPlainText = AESDecrypt($arr['encryptData'], $decryptAESKey);

    // step9: 使用公钥验签报文
    verify($decryptPlainText, $arr['sign'], $pubKey);
} catch (\Exception $e) {
    echo $e->getMessage();
    exit;
}

print_r($decryptPlainText);